package service;

import dao.FansDao;
import dao.UserDao;
import entry.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/fans")
public class FansServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int authorId = Integer.parseInt(req.getParameter("authorId"));
        String concern = req.getParameter("concern");
        String cancel = req.getParameter("cancel");
        HttpSession session = req.getSession(false);
        User user = (User)session.getAttribute("user");
        FansDao fansDao = new FansDao();

        // 是要关注用户
        if (concern != null && concern.equals("yes")){
            fansDao.addFans(authorId, user.getUserId());
            resp.getWriter().write("yes");
            return;
        }
        // 是要取消关注
        if (cancel != null && cancel.equals("yes")){
            fansDao.deleteFans(authorId, user.getUserId());
            resp.getWriter().write("yes");
            return;
        }

        // 是要验证是否显示关注按钮
        if (user.getUserId() == authorId){
            // 是当前用户, 不显示关注按钮
            resp.getWriter().write("no");
            return;
        }
        User fans = fansDao.isFans(authorId, user.getUserId());
        if (fans != null){
            resp.getWriter().write("concerned");
            return;
        }
        resp.getWriter().write("yes");
    }
}
